package com.princess.demok.view.bessel;

import android.animation.Keyframe;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;

import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import androidx.annotation.Nullable;

public class KeyframeView extends View {

    float progress = 0;
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public KeyframeView(Context context) {
        super(context);
    }

    public KeyframeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public KeyframeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    {
        paint.setTextSize(dpToPixel(40));
        paint.setTextAlign(Paint.Align.CENTER);
    }

    public float getProgress() {
        return progress;
    }

    public void setProgress(float progress) {
        this.progress = progress;
        invalidate();
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setColor(Color.parseColor("#E91E63"));
        paint.setStyle(Paint.Style.STROKE);

        paint.setStrokeWidth(dpToPixel(4));

        Path path = new Path();
        //贝赛尔的起始点moveTo(x,y)
        path.moveTo(0, getHeight() / 2);
        //quadTo 参数讲解(x1,y1,x2,y2)
        //x1:控制点x坐标
        //y1:在控制点y坐标
        //x2：终点x坐标
        //y2:终点y坐标
        path.quadTo(getWidth() / 4, 0, getWidth() / 2, getHeight() / 2);
        path.quadTo(getWidth() / 4 * 3, getHeight(), getWidth(), getHeight() / 2);
        canvas.drawPath(path, paint);

        paint.setColor(Color.parseColor("#ffffff"));
        paint.setStyle(Paint.Style.FILL);
        canvas.drawRect(progress / 100*getWidth(), 0, getWidth(), getHeight(), paint);

    }

    public float dpToPixel(float dp) {
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        return dp * metrics.density;
    }

    public void startAnimation(View view){
        Keyframe keyframe1 = Keyframe.ofFloat(0, 0); // 开始：progress 为 0
        Keyframe keyframe2 = Keyframe.ofFloat(1f, 100);
        PropertyValuesHolder holder = PropertyValuesHolder.ofKeyframe("progress", keyframe1, keyframe2);

        ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(view, holder);
        animator.setDuration(2500);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.start();
    }

}
